package com.sj.parksdk.fragment.certificate;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;

import androidx.appcompat.widget.AppCompatImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.net.base.CommonResult;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.manager.TokenManager;
import com.sj.parksdk.net.result.databean.Data_Ocr_ID;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView;
import com.xuexiang.xutil.common.StringUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Page(name = "身份认证")
public class FragmentUserIdCertificate extends BaseFragment {
    @BindView(R2.id.iv_id_back)
    AppCompatImageView ivIdBack;
    @BindView(R2.id.iv_id_front)
    AppCompatImageView ivIdFront;
    @BindView(R2.id.ll_idcard_content)
    LinearLayout llIdcardContent;
    @BindView(R2.id.stv_name)
    SuperTextView stvName;
    @BindView(R2.id.stv_idnumber)
    SuperTextView stvIdnumber;
    @BindView(R2.id.stv_time)
    SuperTextView stvTime;
    @BindView(R2.id.btn_submit)
    SuperButton btnSubmit;

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_userid_certificate;
    }

    @Override
    protected void initViews() {

    }

    @OnClick({R2.id.iv_id_back, R2.id.iv_id_front, R2.id.btn_submit})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_id_back) {
            selectePicture(Extras.REQUEST_PICTURE_BACK);
        } else if (id == R.id.iv_id_front) {
            selectePicture(Extras.REQUEST_PICTURE_FRONT);
        } else if (id == R.id.btn_submit) {
            if (checkData()) showConfirmDialog();
        }
    }

    private boolean checkData() {
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(idNo)) {
            XToastUtils.warning("识别信息有误，请重新上传人像面照片");
            return false;
        }
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            XToastUtils.warning("识别信息有误，请重新上传国徽面照片");
            return false;
        }
        return true;
    }

    private void selectePicture(int code) {
        Utils.getPictureSelector(this)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(code);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Extras.REQUEST_PICTURE_FRONT:
                    // 正面
                    handlerPic(data, 0);
                    break;
                case Extras.REQUEST_PICTURE_BACK:
                    // 背面
                    handlerPic(data, 1);
                    break;
                default:
                    break;
            }
        }
    }

    private void handlerPic(Intent data, int flag) {
        String path = getPicPath(data);
        if (StringUtils.isEmpty(path)) return;
        disPalyPic(flag == 0 ? ivIdFront : ivIdBack, path);
        llIdcardContent.setVisibility(View.VISIBLE);
        queryOCRdata(path, flag);
    }

    private void disPalyPic(AppCompatImageView iv, String paht) {
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.color.color_f4)
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(getContext())
                .load(paht)
                .apply(options)
                .into(iv);
    }

    private String getPicPath(Intent data) {
        List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
        if (list == null || list.size() == 0) {
            XToastUtils.error("选择图片出现错误");
            return "";
        }
        LocalMedia media = list.get(0);
        if (media == null) return "";
        int mimeType = media.getMimeType();
        if (mimeType == PictureMimeType.ofAudio()) {
            XToastUtils.warning("只能选择图片");
            return "";
        }
        String path;
        if (media.isCut() && !media.isCompressed()) {
            // 裁剪过
            path = media.getCutPath();
        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = media.getCompressPath();
        } else {
            // 原图
            path = media.getPath();
        }
        return path;
    }

    @SuppressLint("CheckResult")
    private void queryOCRdata(String path, int flag) {
        File file = new File(path);
        if (!file.exists()) {
            XToastUtils.error("识别失败,未找到文件");
            return;
        }
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .ocridcard(flag == 0 ? "face" : "back", file))
                .subscribeWith(new TipRequestSubscriber<Data_Ocr_ID>() {
                    @Override
                    protected void onSuccess(Data_Ocr_ID data) {
                        setOCRdata(data, flag);
                    }

                    @Override
                    public void onError(ApiException e) {
                        XToastUtils.error(StringUtils.isEmpty(e.getMessage()) ? "识别出错,请重新尝试" : e.getMessage());
                    }
                });
    }

    private String name, idNo, startDate, endDate;

    private void setOCRdata(Data_Ocr_ID data, int flag) {
        if (flag == 0) {
            name = data.getName();
            idNo = data.getIdNo();
            stvName.setCenterEditString(name);
            stvIdnumber.setCenterString(idNo);
        } else if (flag == 1) {
            startDate = data.getStartDate();
            endDate = data.getEndDate();
            stvTime.setCenterString(startDate + "~" + endDate);
        }
    }

    private void showConfirmDialog() {
        StringBuffer sb = new StringBuffer();
        sb.append("姓名：")
                .append(name)
                .append("\n")
                .append("身份证号：")
                .append(idNo)
                .append("\n")
                .append("有效期：")
                .append(startDate)
                .append("~")
                .append(endDate);
        new SweetAlertDialog(getContext(), SweetAlertDialog.CONFIRM_TYPE)
                .setTitleText("请确认以下信息")
                .setConfirmContent("确认无误后请点击确认提交，如有错误请点击取消并重新拍摄上传")
                .setConfirmTitle(sb.toString())
                .setCancelClickListener(null)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDilaog) {
                        sDilaog.dismiss();
                        submitConfirmData();
                    }
                }).show();
    }

    @SuppressLint("CheckResult")
    private void submitConfirmData() {
        CustomRequest request = XHttp.custom();
        request.call(ApiHelper.getInstance(request)
                .userVerify(name, idNo, startDate, endDate))
                .subscribeWith(new TipRequestSubscriber<CommonResult>() {
                    @Override
                    protected void onSuccess(CommonResult result) {
                        if (result.getCode() == 200) showSuccessDialog();
                        else showFailedDialog();
                    }

                    @Override
                    public void onError(ApiException e) {
                        showFailedDialog();
                    }
                });
    }

    private void showSuccessDialog() {
        new SweetAlertDialog(getContext(), SweetAlertDialog.SUCCESS_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setContentText("认证成功")
                .showCancelButton(false)
                .setConfirmText("返回")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        showSuccessDialog();
                        TokenManager.getInstance().refreshLoginState(true);
                        popToBack();
                    }
                }).show();
    }

    private void showFailedDialog() {
        new SweetAlertDialog(getContext(), SweetAlertDialog.ERROR_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setContentText("认证失败,请再试一次")
                .showCancelButton(false)
                .setConfirmText("好的")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                    }
                }).show();
    }
}
